package com.sunlake.spring.main.model.article.service.impl;

import com.github.pagehelper.PageHelper;
import com.sunlake.spring.main.common.model.file.mapper.FilesMapper;
import com.sunlake.spring.main.common.response.R;
import com.sunlake.spring.main.common.utils.CurrentUserUtil;
import com.sunlake.spring.main.common.utils.JwtTokenUtil;
import com.sunlake.spring.main.common.utils.LoggerUtil;
import com.sunlake.spring.main.common.utils.RedisUtils;
import com.sunlake.spring.main.model.article.dto.CreateArticlesDTO;
import com.sunlake.spring.main.model.article.dto.FetchArticlesDTO;
import com.sunlake.spring.main.model.article.mapper.ArticleCommentsMapper;
import com.sunlake.spring.main.model.article.mapper.ArticlesMapper;
import com.sunlake.spring.main.model.article.po.ArticlesPO;
import com.sunlake.spring.main.model.article.service.ArticleService;
import com.sunlake.spring.main.model.auth.mapper.UsersMapper;
import com.sunlake.spring.main.model.auth.po.UsersPO;
import com.sunlake.spring.main.model.counselor.po.FilesPO;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    private static final Logger log = LoggerUtil.getLogger(ArticleServiceImpl.class);

    private final JwtTokenUtil jwtTokenUtil;
    @Value("${file.upload-dir}")
    private String UPLOAD_DIR;

    // 规范化后的绝对根路径
    private Path rootUploadDir;
    @Autowired
    private UsersMapper usersMapper;

    public ArticleServiceImpl(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Autowired
    private FilesMapper filesMapper;

    @Autowired
    private ArticlesMapper articlesMapper;

    @Autowired
    private ArticleCommentsMapper articleCommentsMapper;

    @Autowired
    private RedisUtils redisUtils;

    public R fetchArticles(FetchArticlesDTO fetchArticlesDTO) {

        // 分页参数
        int page = fetchArticlesDTO.getPage();
        int size = fetchArticlesDTO.getSize();
        String category = fetchArticlesDTO.getCategory();
        String keyword = fetchArticlesDTO.getKeyword();
        PageHelper.startPage(page,size);
        if(keyword==null||"".equals(keyword)){
            keyword="";
        }
        List<ArticlesPO> articles ;
        if(category.equals("RECOMMEND"))
        {
            articles = articlesMapper.selectByKeyword(keyword);
        }
        else
        {
            articles = articlesMapper.selectByCategoryAndKeyword(category, keyword);
        }
        System.out.println(articles);
        return R.ok(200,"文章获取成功", articles);
    }
    @Override
    public R<String> createArticle(CreateArticlesDTO createArticlesDTO) {
        Long userId = CurrentUserUtil.getCurrentUserId();
        if(userId == null) {
            return R.error(401,"用户未登录");
        }

        ArticlesPO articles = new ArticlesPO();
        articles.setAuthorId(userId.intValue());
        articles.setTitle(createArticlesDTO.getTitle());
        articles.setCoverImage(createArticlesDTO.getCoverUrl());
        articles.setCategory(createArticlesDTO.getCategory());
        articles.setDescription(createArticlesDTO.getDescription());
        articles.setContent(createArticlesDTO.getContent());
        articles.setTags(createArticlesDTO.getTags());
        articles.setStatus(createArticlesDTO.getStatus());
        articles.setViewCount(0);
        articles.setFavoriteCount(0);
        articles.setCreatedAt(LocalDateTime.now());
        articles.setUpdatedAt(LocalDateTime.now());

        articlesMapper.insert(articles);

        return R.ok(200,"文章创建成功");
    }

    @Override
    public R uploadCover(MultipartFile file) {
        // 将图片存储在本地
        Path configured = Paths.get(UPLOAD_DIR);

        if (!configured.isAbsolute()) {
            configured = Paths.get(System.getProperty("user.dir")).resolve(configured).normalize();
        } else {
            configured = configured.normalize();
        }
        this.rootUploadDir = configured;
        rootUploadDir = rootUploadDir.resolve("cover");

        try {
            Files.createDirectories(rootUploadDir);
            log.info("上传根目录: {}", rootUploadDir);
        } catch (IOException e) {
            log.error("创建上传目录失败: {}", e.getMessage(), e);
        }

        Long userId = CurrentUserUtil.getCurrentUserId();
        if(userId == null) {
            return R.error(401,"用户未登录");
        }

        UsersPO user = usersMapper.selectByPrimaryKey(userId);
        String username = user.getUsername();

        String originalFilename = file.getOriginalFilename();
        String extension = (originalFilename != null && originalFilename.lastIndexOf('.') >= 0)
                ? originalFilename.substring(originalFilename.lastIndexOf('.') + 1)
                : "";
        String fileName = username + "_" + userId + "_" + System.currentTimeMillis() + "." + extension.toLowerCase();
        Path filePath = rootUploadDir.resolve(fileName);

        try {
            file.transferTo(filePath.toFile());
            log.info("文件上传成功: {}", filePath);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return R.error(500, "文件上传失败");
        }

        FilesPO filesPO = new FilesPO();
        filesPO.setFilename(fileName);
        filesPO.setFileUrl(filePath.toString());
        filesPO.setFileSize(file.getSize());
        filesPO.setCreatedAt(LocalDateTime.now());
        filesPO.setUploaderId(Math.toIntExact(userId));
        filesMapper.insert(filesPO);

        HashMap<String,Object> result = new HashMap<>();
        result.put("coverUrl", filePath.toString());
        return R.ok(200,"文件上传成功", result);
    }
}
